﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace LayoutLoggingService.Client
{
    /// <summary>
    /// Abstracts the service.
    /// </summary>
    public class Service
    {
        public Uri Uri { get; set; }

        public Response LogLayout(Request request)
        {
            // build HTTP request
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
            httpRequest.Method = "POST";
            httpRequest.ContentType = "text/xml";
            httpRequest.ContentLength = request.Payload.Length;
            httpRequest.KeepAlive = false;
            httpRequest.ProtocolVersion = HttpVersion.Version10;
            if (request.Header != null)
            {
                foreach (var header in request.Header.AllKeys)
                {
                    httpRequest.Headers[header] = request.Header[header];
                }
            }

            HttpWebResponse httpResponse = null;
            try
            {
                // make the call and get HTTP response
                using (Stream rqStr = httpRequest.GetRequestStream())
                {
                    byte[] data = Encoding.ASCII.GetBytes(request.Payload);
                    rqStr.Write(data, 0, data.Length);
                    bool isError;
                    try
                    {
                        httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                        isError = false;
                    }
                    catch (WebException e)
                    {
                        httpResponse = (HttpWebResponse)e.Response;
                        if (httpResponse == null)
                        {
                            throw new Exception(e.Message, e);
                        }
                        isError = true;
                    }

                    // build Response object
                    Response response = new Response();
                    response.StatusCode = System.Convert.ToInt32(httpResponse.StatusCode);
                    response.ReasonPhrase = httpResponse.StatusDescription;
                    if (isError)
                    {
                        response.ErrorMessage = httpResponse.Headers["X-Search-ErrorMessage"];
                    }

                    // return
                    return response;
                }
            }
            finally
            {
                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
            }
        }
    }
}

